﻿#include "textedit.h"
#include <QFile>
#include <QFileInfo>
#include <QFileDialog>
#include <QTextDocumentWriter>
#include <QCloseEvent>
#include <QMessageBox>

TextEdit::TextEdit(QWidget*parent):QTextEdit(parent),docwindowTitle(""),docName("")
{
    setAttribute(Qt::WA_DeleteOnClose);
}
int TextEdit::docNo=1;

bool TextEdit::initNewDoc()
{
    docwindowTitle="文档 "+QString::number(docNo++);
    setWindowTitle(docwindowTitle+"[*]");
    connect(document(),&QTextDocument::contentsChanged,this,&TextEdit::setWindowModify);
}

QString TextEdit::getDocName()
{
    return docName;
}

bool TextEdit::loadDoc(const QString &filename)
{
    if(!filename.isEmpty())
    {
        QFile file(filename);
        if(!file.exists())return false;
        if(!file.open(QFile::ReadOnly))return false;
        QByteArray text=file.readAll();
        if(Qt::mightBeRichText(text))
        {
            setHtml(text);
        }
        else
        {
            setPlainText(text);
        }
        initOpenDoc(filename);
    }
    return true;
}

void TextEdit::initOpenDoc(const QString &filename)
{
    docName=QFileInfo(filename).canonicalFilePath();
    docwindowTitle=QFileInfo(getDocName()).fileName()+QString::number(docNo++);
    setWindowTitle(docwindowTitle+"[*]");
    connect(document(),SIGNAL(contentsChanged()),this,SLOT(setWindowModify()));
}

bool TextEdit::saveDoc()
{
    if(!document()->isModified())return false;
    if(!docName.isEmpty())
    {
        return writeToDoc(docName);
    }
    else
    {
        return saveAsDoc();
    }
}

bool TextEdit::saveAsDoc()
{
    QString filename=QFileDialog::getSaveFileName(this,"保存文件","../","文本文件(*.txt);;html文件(*.html)");
    if(filename.isEmpty())return false;
    return writeToDoc(filename);
}

QString TextEdit::getWindoTitle() const
{
    return this->docwindowTitle;
}

void TextEdit::setWindowModify()
{
    bool isModify=document()->isModified();
    setWindowModified(isModify);
}

bool TextEdit::writeToDoc(const QString&filename)
{
    QTextDocumentWriter writer(filename);
    if(writer.write(document()))
    {
        docName=QFileInfo(filename).canonicalFilePath();
        document()->setModified(false);
        setWindowModified(false);
    }

}

void TextEdit::closeEvent(QCloseEvent *event)
{
    if(!document()->isModified())return;
    //QString name=QFileInfo(getDocName()).fileName();
    QMessageBox::StandardButton res;
    res=QMessageBox::warning(this,"确定退出?",docwindowTitle+"已经修改是否保存?",
                             QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel);
     if(res==QMessageBox::Yes)
     {
         saveDoc();
     }
     else if(res==QMessageBox::No)
     {
         event->accept();
     }
     else if(res==QMessageBox::Cancel)
     {
         event->ignore();
     }

}
